package com.spsoft.vatoutinv.service.flowprocess;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.BusinessException;
import com.spsoft.core.model.ProcessParamBo;
import com.spsoft.core.model.Result;
import com.spsoft.system.entity.NvatOutInvoiceItems;
import com.spsoft.system.mapper.NvatOutInvoiceItemsMapper;
import com.spsoft.vatoutinv.entity.matchflow.VmsMatching;
import com.spsoft.vatoutinv.entity.matchflow.VmsMatchingDetail;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchFlowService;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchingDetailService;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchingService;
import com.spsoft.workflow.common.enums.bus.MatchFlowEnums;
import com.spsoft.workflow.service.BusinessHandlerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 发票匹配流水申请流程处理业务实现类
 *
 * @author : chenxudong
 * @date : 2024/6/27 16:25
 */
@Service("FLOW_PPLS")
@Slf4j
@RequiredArgsConstructor
public class MatchFlowProcessHandlerServiceImpl implements BusinessHandlerService {

    private final VmsMatchingService vmsMatchingService;

    private final VmsMatchingDetailService vmsMatchingDetailService;

    private final VmsMatchFlowService vmsMatchFlowService;

    private final NvatOutInvoiceItemsMapper nvatOutInvoiceItemsMapper;

    @Override
    public void processHandler(ProcessParamBo param) throws BusinessException {
        Long busId = param.getBusId();
        String nodeId = param.getNodeId();
        Boolean submit = param.getSubmit();
        MatchFlowEnums e = MatchFlowEnums.valueOfCode(nodeId);
        if (e == null) {
            throw new BusinessException(ResponseEnum.PARAM_VALIDATED_ERROR.getCode(), "审批流程有误，请联系管理员");
        }
        switch (e) {
            case ROOT:
                /**
                 * 保存时，发票明细可以没有匹配流水
                 * 提交时，发票明细需要匹配上流水
                 */
                // 查询手工匹配流水信息
                LambdaQueryWrapper<VmsMatching> matchQuery = new LambdaQueryWrapper<>();
                matchQuery.eq(VmsMatching::getApplyId, busId);
                VmsMatching vmsMatching = vmsMatchingService.getOne(matchQuery);
                if (vmsMatching == null) {
                    throw new BusinessException(ResponseEnum.MATCH_FLOW_NOT_FIND_ERROR);
                }

                // 提交流程校验
                if (submit) {
                    // 查询发票明细信息
                    LambdaQueryWrapper<NvatOutInvoiceItems> itemQuery = new LambdaQueryWrapper<>();
                    itemQuery.eq(NvatOutInvoiceItems::getOidid, vmsMatching.getOidid());
                    itemQuery.orderByAsc(NvatOutInvoiceItems::getIviid);
                    List<NvatOutInvoiceItems> nvatOutInvoiceItemList = nvatOutInvoiceItemsMapper.selectList(itemQuery);

                    // 查询明细匹配流水信息
                    LambdaQueryWrapper<VmsMatchingDetail> detailQuery = new LambdaQueryWrapper<>();
                    detailQuery.eq(VmsMatchingDetail::getMatid, vmsMatching.getMatid());
                    detailQuery.orderByAsc(VmsMatchingDetail::getMatdeid);
                    List<VmsMatchingDetail> matchDetailList = vmsMatchingDetailService.list(detailQuery);
                    if (CollectionUtil.isEmpty(matchDetailList)) {
                        throw new BusinessException(ResponseEnum.ITEM_NOT_MATCH_FLOW_ERROR);
                    }

                    // 每一条发票明细都需要匹配上流水才可以提交
                    for (NvatOutInvoiceItems nvatOutInvoiceItem : nvatOutInvoiceItemList) {
                        Optional<VmsMatchingDetail> first = matchDetailList.stream().filter(a -> nvatOutInvoiceItem.getIviid().equals(a.getIviid())).findFirst();
                        if (!first.isPresent()) {
                            throw new BusinessException(ResponseEnum.ITEM_NOT_MATCH_FLOW_ERROR);
                        }
                    }
                }
                break;
            case FLOW_PPLS_SP:
                /**
                 * 审批节点
                 * 1、判断当前发票的匹配状态是否为未匹配、明细匹配的流水是否为未开票状态
                 * 2、将发票明细和匹配的流水在关联关系表中进行关联
                 * 3、将流水的开票状态修改为已开票、发票的匹配状态修改为已匹配、记录匹配时间
                 */
                Result<Object> result = vmsMatchFlowService.matchFlowProcess(busId);
                if (!ResponseEnum.SUCCESS.getCode().equals(result.getCode())) {
                    throw new BusinessException(result.getCode(), result.getMessage());
                }
                break;
            default:
                // 未知节点报错
                throw new BusinessException(ResponseEnum.PROCESS_NODE_ERROR);
        }
    }
}
